<template>
    <div class="account-sub-main">
        <ZwTableSearch :option="searchOption" @search="onSearch" @reset="onReset" @expand="getTableH" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button v-auth="'ADD_SUB_ACCOUNT'" type="primary" @click="addSub">添加子账号</el-button>
            </template>
        </ZwTable>
    </div>

    <el-drawer
        v-model="showDrawer"
        custom-class="zw_drawer"
        :title="openType == 1 ? '添加子账号' : openType == 2 ? '子账号详情' : '编辑子账号'">
        <template #default>
            <div class="content">
                <el-scrollbar class="main">
                    <el-form ref="uploadForm" label-width="90px" class="add-member" :model="formData" :rules="rules">
                        <el-form-item label="账号名称" class="form-item" prop="name">
                            <el-input
                                v-model="formData.name"
                                placeholder="请输入账号名称"
                                class="form-label"
                                :disabled="openType == 2"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号码" class="form-item" prop="phone">
                            <el-input
                                v-model="formData.phone"
                                placeholder="请输入手机号码"
                                class="form-label"
                                :disabled="openType == 2 || openType == 3"
                                @input="getPhoneNum"></el-input>
                        </el-form-item>
                        <el-form-item label="性别" class="form-item" prop="sex">
                            <el-radio v-model="formData.sex" :label="1" :disabled="openType == 2 || isSex">男</el-radio>
                            <el-radio v-model="formData.sex" :label="2" :disabled="openType == 2 || isSex">女</el-radio>
                        </el-form-item>
                        <el-form-item label="职务" class="form-item">
                            <el-input
                                v-model="formData.position"
                                placeholder="请输入部门职务名称，例如：销售顾问"
                                class="form-label"
                                :disabled="openType == 2 || isPosition">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="状态" class="form-item" prop="status">
                            <el-radio v-model="formData.status" :label="1" :disabled="openType == 2 || isStatus">
                                正常启用
                            </el-radio>
                            <el-radio v-model="formData.status" :label="2" :disabled="openType == 2 || isStatus">
                                禁用
                            </el-radio>
                        </el-form-item>
                        <el-form-item label="角色" class="form-item" prop="role_id">
                            <el-select
                                v-model="formData.role_id"
                                value-key="id"
                                placeholder="请选择"
                                class="form-label"
                                :disabled="openType == 2 || isRole || isDisabled">
                                <el-option
                                    v-for="item in roleLists"
                                    :key="item.id"
                                    :disabled="item.name === '超级管理员'"
                                    :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="绑定员工">
                            <el-select
                                v-model="formData.execute_workuser_id"
                                multiple
                                popper-class="zw-hide_select_option"
                                :disabled="openType == 2 || isPosition"
                                @click="opendept(domember)"
                                @change="changedept">
                                <el-option v-for="item in domember" :key="item.id" :label="item.name" :value="item.id">
                                    {{ item.name }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-show="isShow" label="客易达">
                            <el-switch
                                v-model="formData.enable_assistant"
                                :disabled="openType == 2 || isPosition"></el-switch>
                        </el-form-item>
                        <el-form-item v-if="hidePassword" label="设置密码" class="form-item" prop="password">
                            <el-input v-model="formData.password" type="password" show-password></el-input>
                        </el-form-item>
                        <el-form-item v-if="openType !== 2" class="form-item"> </el-form-item>
                    </el-form>
                </el-scrollbar>
            </div>
        </template>
        <template #footer>
            <div v-if="openType !== 2">
                <el-button type="primary" @click="addCount">提交</el-button>
                <el-button @click="clearAll">重置</el-button>
            </div>
        </template>
    </el-drawer>
    <!--选择部门弹出框-->
    <el-dialog v-model="departVisible" title="选择部门" width="35%" append-to-body class="depart-select">
        <div class="depart-content">
            <div>
                <el-input
                    v-model="companyName"
                    style="width: 240px"
                    suffix-icon="Search"
                    placeholder="搜索部门"
                    @input="searchName"></el-input>
                <el-tree
                    v-if="!companyName"
                    default-expand-all
                    :data="treeData"
                    :props="defaultProps"
                    @node-click="nodeClick">
                    <template #default="{ data }">
                        <div :class="selectId == data.id ? 'hover-detail-color' : 'hover-detail'">
                            {{ data.name
                            }}<span :class="data.is_local ? 'local-color' : 'detail-color'">{{
                                data.is_local ? '(本地)' : '(企微)'
                            }}</span>
                        </div>
                    </template>
                </el-tree>
                <div v-if="searchTree.length > 0" class="depart-detail">
                    <el-button
                        v-for="(item, index) in searchTree"
                        :key="index"
                        class="depart-btn"
                        type="text"
                        @click="nodeClick(item)">
                        {{ item.name }}
                        <span :class="item.is_local ? 'local-color' : 'detail-color'">
                            {{ item.is_local ? '(本地)' : '(企微)' }}
                        </span>
                    </el-button>
                </div>
                <div v-if="searchTree.length == 0 && companyName" class="no-data">
                    <img src="@/assets/noData.png" class="no-img" />
                    <span class="no-span">暂无数据</span>
                </div>
            </div>
            <div>
                <div>
                    已选择的部门：
                    <div v-for="(item, index) in dialogMember" :key="index" class="select-detail select-details">
                        <div>{{ item.name }}</div>
                        <el-icon v-show="item.name" style="font-size: 25px" @click="deldelectDeparts(item)">
                            <circle-close />
                        </el-icon>
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancelchoose">取消</el-button>
                <el-button type="primary" @click="addsubmit">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!--重置密码弹框-->
    <el-dialog v-model="passwordVisible" title="重置密码" width="450">
        <div>
            <el-input v-model="qrcode" placeholder="请输入验证码" style="width: 300px; margin-right: 30px"></el-input>
            <el-link v-show="sendAuthCode" :underline="false" type="primary" @click="getCode">获取验证码</el-link>
            <div class="tips-text">验证码成功后，密码将会重置为<span class="tips-detail">kyd123456</span></div>
            <span v-show="!sendAuthCode" style="color: #ff6b00">{{ autoTime }}后重新获取</span>
        </div>
        <template #footer>
            <el-button @click="passwordVisible = false">取消</el-button>
            <el-button type="primary" @click="initCodes">确定</el-button>
        </template>
    </el-dialog>
    <!--修改权限弹框-->
    <Dialog :app-dialog="appDialog">
        <EditRole ref="editRoleRef" :permission-id="permissionId"></EditRole>
    </Dialog>
    <ZWDepart ref="DepartRef" :type="1" @submit="getDepart"></ZWDepart>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'SUBACCOUNT_MANAGEMENT' });
</script>

<script lang="tsx" setup>
import ZwTableSearch from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import EditRole from './components/EditRole.vue';
import Search from './components/Search.vue';
import Table from './components/Table.vue';
import Dialog from '@/components/Dialog.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import { getSetionId, tableH, reSize } from '@/utils/utils';

import { ref, reactive, nextTick, computed, toRefs, onMounted } from 'vue';
import {
    subAcountList,
    addSubAcount,
    roleList,
    updateAccount,
    resetCode,
    initPassword,
    menuAuth,
    updateMenuAuth,
    getWorkUser,
    disableAccount,
    delAccount
} from '@/api/sub';
import { searchTreeList, fetchTreeList } from '@/api/employee';
import { ISearch } from './type/index';
import { ElMessage, ElButton, ElTag, ElMessageBox } from 'element-plus';

import { deepCopy } from '@/utils/helper';
const isDisabled = ref(false);
const tableRef = ref();
const DepartRef = ref(null);
const searchOption = [
    {
        label: '账号信息',
        name: 'mobile_or_account_name',
        value: '',
        type: 'input',
        placeholder: '请输入手机号/账号姓名'
    },
    {
        label: '账号状态',
        name: 'account_status',
        value: [],
        type: 'select',
        placeholder: '请选择账号状态',
        formatOption: (v: any) => ({
            label: v.label,
            value: v.value
        }),
        optionList: [
            {
                value: '-1',
                label: '全部'
            },
            {
                value: '2',
                label: '已禁用'
            },
            {
                value: '1',
                label: '已启用'
            }
        ]
    },
    {
        label: '账号角色',
        name: 'account_role',
        value: [],
        type: 'select',
        placeholder: '请选择账号角色',
        formatOption: (v: any) => ({
            label: v.name,
            value: v.id
        }),
        fetchOptionApi: () => {
            return new Promise(resolve => {
                roleList().then((data: any) => {
                    data.forEach((item: any) => {
                        if (item.name == '超级管理员') {
                            data.splice(data.indexOf(item as never), 1);
                        }
                    });
                    resolve(data);
                });
            });
        }
    }
];

const tableOption = [
    // {
    //   type: 'selection',
    //   width: 55,
    //   fixed: 'left',
    //   reserveSelection: true
    // },
    {
        prop: 'name',
        label: '账号姓名',
        minWidth: 100,
        render({ row, column, index }: any) {
            return (
                <div style="display: flex;align-items: center;">
                    <span>{row.name}</span>
                    {row.sex_name ? (
                        <span
                            style={
                                row.sex == 1
                                    ? 'display: flex;justify-content: center;align-items: center; width: 18px;height: 18px;margin-left: 6px;border-radius: 50%;color: #ffffff;background-color: #75ddf4;'
                                    : 'display: flex;justify-content: center;align-items: center; width: 18px;height: 18px;margin-left: 6px;border-radius: 50%;color: #ffffff;background-color: #f474bf;'
                            }>
                            {row.sex_name}
                        </span>
                    ) : (
                        ''
                    )}
                </div>
            );
        }
    },
    {
        prop: 'phone',
        label: '手机号',
        minWidth: 140
    },
    {
        prop: 'name',
        label: '账号角色',
        render({ row, column, index }: any) {
            return row.account_type == 1 ? '主账号' : row.role.length > 0 ? row.role[0].name : '-';
        }
    },
    // {
    //   prop: 'department',
    //   label: '部门',
    //   minWidth: 200,
    //   render({ row, column, index }: any) {
    //     const dom = row.department.map((item: any, index: number) => {
    //       return (
    //         <ElTag style="margin: 5px" size="small" type="warning">
    //           {item.name}
    //         </ElTag>
    //       )
    //     })
    //     return row.department.length > 0 ? <div style="margin: -5px">{dom}</div> : '--'
    //   }
    // },
    {
        prop: 'work_user',
        label: '绑定企微员工',
        minWidth: 200,
        render({ row, column, index }: any) {
            return row.work_user?.name || '--';
        }
    },
    {
        prop: 'status_name',
        label: '状态'
    },
    {
        prop: 'created_at',
        label: '添加时间',
        minWidth: 200
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }: any) {
            const option = [
                {
                    id: 0,
                    name: '查看',
                    n: 1,
                    isShow: true,
                    click: (row: any) => handleDetail(row, 2)
                },
                {
                    id: 1,
                    name: '编辑',
                    n: 1,
                    isShow: true,
                    click: (row: any) => handleDetail(row, 1)
                },
                {
                    id: 2,
                    name: '禁用',
                    isShow: row.status == 1,
                    click: (row: any) => onDisableOpen(row)
                },
                {
                    id: 3,
                    name: '开启',
                    isShow: row.status == 2,
                    click: (row: any) => onDisableOpen(row)
                },
                {
                    id: 3,
                    name: '重置密码',
                    n: 1,
                    isShow: true,
                    click: (row: any) => onHandlePassword(row)
                },
                {
                    id: 3,
                    name: '修改权限',
                    isShow: true,
                    click: (row: any) => onHandlePermission(row)
                },
                { id: 3, name: '删除', isShow: true, click: (row: any) => del(row) }
            ];
            return option.map((item, itemIndex) =>
                item.isShow ? (
                    <ElButton
                        size="small"
                        vShow={row.account_type == 2 ? 'true' : row.account_type == item.n}
                        onClick={() => item.click(row)}
                        key={`${item.id}-${itemIndex}`}>
                        {item.name}
                    </ElButton>
                ) : (
                    ''
                )
            );
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const defaultParams = {};
const editRoleRef = ref();
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const appDialog = reactive({
    visible: false,
    title: '修改权限',
    width: '500px',
    isDisable: false,
    cancelText: '取消',
    submitText: '保存',
    cancel: () => {
        appDialog.visible = false;
    },
    submit: () => {
        appDialog.visible = false;
        const paramsData = editRoleRef.value.formData;
        const params = {
            sub_account_id: permissionId.value,
            ...paramsData
        };
        updateMenuAuth(params).then((data: any) => {
            ElMessage.success('修改权限成功！');
            tableRef.value.reload();
        });
    }
});

//获取角色列表
const getRoleList = () => {
    roleList().then((data: any) => {
        // data.forEach((item: any) => {
        //   if (item.name == '超级管理员') {
        //     data.splice(data.indexOf(item as never), 1)
        //     adminInfo.value = item
        //   }
        // })
        roleLists.value = data;
    });
};
getRoleList();
// 获取文件列表
const fetchApi = () => {
    getTableH();
    return subAcountList;
};

// 查询
const onSearch = (v: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = v;
};

// 重置
const onReset = (v: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = deepCopy(defaultParams);
};
// 删除所选部门节点
const deldelectDeparts = (val: any) => {
    dialogMember.value.forEach((item: any, index: any) => {
        if (item.name == val.name) {
            dialogMember.value.splice(index, 1);
            formData.department_ids.pop();
        }
    });
};
//删除所选部门节点
// const deldelectDeparts = (val: any) => {
//   selectDeparts.value.forEach((item: any) => {
//     if (item.name == val.name) {
//       selectDeparts.value.pop()
//       formData.department_ids.pop()
//     }
//   })
// }
const cancelchoose = () => {
    departVisible.value = false;
    dialogMember.value = [];
};
const Opendepart = () => {
    departVisible.value = true;
    dialogMember.value = JSON.parse(JSON.stringify(selectDeparts.value));
};
const addsubmit = () => {
    departVisible.value = false;
    selectDeparts.value = JSON.parse(JSON.stringify(dialogMember.value));
    formData.department_ids = getSetionId('id', selectDeparts.value);
};
//添加子账号
const addSub = () => {
    isStatus.value = false;
    isRole.value = false;
    isSex.value = false;
    formData.execute_workuser_id = [];
    formData.role_id = '';
    hidePassword.value = true;
    isDisabled.value = false;
    // superMember.value = ''
    domember.value = [];
    if (uploadForm.value) {
        uploadForm.value.resetFields();
    }
    openType.value = 1;
    showDrawer.value = true;
    clearAll();
};

//启用禁用
const onDisableOpen = (row: any) => {
    const params = {
        sub_account_id: row.id,
        status: row.status == 1 ? 2 : 1
    };
    ElMessageBox({
        title: '提示',
        message: `是否${row.status == 1 ? '禁用' : '启用'}【${row.name}】?`,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        type: 'warning'
    })
        .then(() => {
            disableAccount(params).then(() => {
                ElMessage({
                    message: `${row.status == 1 ? '禁用' : '启用'}成功`,
                    type: 'success'
                });
                tableRef.value.reload();
            });
        })
        .catch(() => {});
};

//重置密码
const onHandlePassword = (data: any) => {
    passwordVisible.value = true;
    sendAuthCode.value = true;
    formData.sub_account_id = data.id;
};

//修改权限
const onHandlePermission = (data: any) => {
    appDialog.visible = true;
    permissionId.value = data.id;
    //getMenuAuth(data.id)
};
// 删除当前账号
const del = (data: any) => {
    ElMessageBox.confirm('删除后该账号将无法登录，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then(async () => {
        await delAccount({ user_id: data.id });
        tableRef.value.reload();
        ElMessage({
            type: 'success',
            message: '删除成功'
        });
    });
};
const showDrawer = ref(false);
const departVisible = ref(false);
const passwordVisible = ref(false);
const isShow = ref(false);
const openType = ref(1); //1添加子账号2查看子账号详情3编辑子账号
const tenantList = ref([]); //权限
const disableIds = ref([]);
const uploadForm = ref();
const companyName = ref();
const qrcode = ref();
const Departmantname = ref();
const searchTree = ref([]);
const treeData = ref([]);
const roleLists = ref([]);
const autoTime = ref(0);
const sendAuthCode = ref(true);
const isSex = ref(false);
const isPosition = ref(false);
const isStatus = ref(false);
const isRole = ref(false);
const isUser = ref(false);
const selectId = ref(0);
const permissionId = ref(0);
const dialogMember = ref([]); //弹框选中的
const selectDeparts = ref([]); //选择的部门
const hidePassword = ref(true);
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
});
const permission = reactive({
    data_permissions: 1,
    data_premission_type: 1
});
const formData = reactive({
    name: '',
    sex: 1,
    phone: '',
    department_ids: [],
    position: '',
    status: 1,
    role_id: '',
    is_sync_qw: 0,
    sub_account_id: '',
    password: '',
    enable_assistant: false,
    execute_workuser_id: []
});
// const subId = ref()
const is_sync_qw = ref(false);
const defaultProps = {
    children: 'children',
    label: 'name'
};
const domember = ref([]);
let account = reactive({});
let work_user = reactive({});
const isRequired = ref(true);
// const superMember = ref()
const rules = reactive({
    name: [
        {
            required: true,
            message: '请输入账号名称',
            trigger: 'blur'
        }
    ],
    phone: [
        {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
        }
    ],
    sex: [
        {
            required: true,
            message: '请选择性别',
            trigger: 'change'
        }
    ],
    status: [
        {
            required: true,
            message: '请选择状态',
            trigger: 'change'
        }
    ],
    role_id: [
        {
            required: true,
            message: '请选择角色',
            trigger: 'change'
        }
    ],
    password: [
        {
            required: isRequired,
            message: '请输入密码',
            trigger: 'blur'
        }
    ]
});

//获取子账号菜单权限
// const getMenuAuth = (val:any) => {
//     subId.value = val
//     const params = {
//         sub_account_id: val
//     }
//     menuAuth(params).then((data:any) => {
//       tenantList.value = data.sub_account_menu_list
//       disableIds.value = data.disable_function_ids
//       permission.data_permissions = data.data_auth.data_permissions
//       permission.data_premission_type = data.data_auth.data_premission_type
//     })
// }

//重置
const clearAll = () => {
    (formData.name = ''),
        (formData.sex = 1),
        (formData.department_ids = []),
        (selectDeparts.value = []),
        (formData.position = ''),
        (formData.status = 1),
        // formData.role_id = roleLists.value[4]['id'],
        (formData.role_id = ''),
        (formData.is_sync_qw = 0),
        (is_sync_qw.value = false);
    formData.sub_account_id = '';
    Departmantname.value = '';
    if (openType.value == 1) {
        formData.phone = '';
    }
};
//新增子账号
const addCount = () => {
    is_sync_qw.value == true ? (formData.is_sync_qw = 1) : (formData.is_sync_qw = 0);
    uploadForm.value.validate(async (valid: any) => {
        if (valid) {
            let params = {};
            params = JSON.parse(JSON.stringify(formData));
            params.execute_workuser_id = formData.execute_workuser_id.length
                ? formData.execute_workuser_id[0] + ''
                : '';
            if (openType.value == 1) {
                addSubAcount(params).then((data: any) => {
                    showDrawer.value = false;
                    ElMessage({
                        message: '新增成功',
                        type: 'success'
                    });
                    tableRef.value.reload();
                });
            } else {
                updateAccount(params).then((data: any) => {
                    showDrawer.value = false;
                    ElMessage({
                        message: '编辑成功',
                        type: 'success'
                    });
                    tableRef.value.reload();
                });
            }
        } else {
            ElMessage.error('请输入必填项！');
        }
    });
};
//搜索部门
const searchName = () => {
    const params = {
        keyword: companyName.value
    };
    searchTreeList(params).then((data: any) => {
        if (data.length > 0) {
            searchTree.value = data;
        } else {
            searchTree.value = [];
        }
    });
};
//获取部门树
const getTreeList = () => {
    treeData.value = [];
    fetchTreeList().then((data: any) => {
        treeData.value.push(data as never);
    });
};
getTreeList();
//选择部门节点
const nodeClick = (data: any, node: any, obj: any) => {
    if (dialogMember.value.indexOf(data as never) == -1) {
        dialogMember.value.push(data as never);
    } else {
        return;
    }
};
//查看详情
const handleDetail = (value: any, type: number) => {
    if (uploadForm.value) {
        uploadForm.value.resetFields();
    }
    if (type == 1) {
        openType.value = 3;
        isUser.value = false;
        domember.value = Array.isArray(value.work_user) ? value.work_user : [value.work_user];
        formData.execute_workuser_id = getSetionId('id', domember.value);
        hidePassword.value = false;
    } else {
        openType.value = 2;
        isUser.value = true;
        domember.value = Array.isArray(value.work_user) ? value.work_user : [value.work_user];
        formData.execute_workuser_id = getSetionId('id', domember.value);
        hidePassword.value = false;
    }
    selectDeparts.value = value.department;
    // Departmantname.value = value.department
    (formData.name = value.name),
        (formData.sex = value.sex),
        (formData.phone = value.phone),
        // formData.department_ids = value.department_ids,
        (formData.position = value.position),
        (formData.status = value.status),
        // formData.is_sync_qw = value.is_sync_qw,
        (formData.sub_account_id = value.id);

    // superMember.value = value.account_type == 1
    // value.role.length > 0 ? (formData.role_id = value.role[0].zw_corp_id == 0 ? '超级管理员' : value.role[0].id) : (formData.role_id = '')

    formData.role_id = value.role[0].id || '';
    isDisabled.value = value.account_type == 1 ? true : false;

    showDrawer.value = true;
    value.is_sync_qw == 1 ? (is_sync_qw.value = true) : (is_sync_qw.value = false);
    value.is_sync_qw == 1 ? (formData.is_sync_qw = 1) : (formData.is_sync_qw = 0);
    formData.enable_assistant = value.enable_assistant;
    value.enable_assistant ? (isShow.value = true) : (isShow.value = false);
    formData.department_ids = [];
    value.department.forEach((item: any) => {
        formData.department_ids.push(item.id as never);
    });
};

//获取验证码
const getCode: () => void = () => {
    sendAuthCode.value = false;
    autoTime.value = 60;
    const autoTimeTimer = setInterval(() => {
        autoTime.value--;
        if (autoTime.value <= 0) {
            sendAuthCode.value = true;
            clearInterval(autoTimeTimer);
        }
    }, 1000);
    getCodeList();
};
//发送验证码请求
const getCodeList = () => {
    const params = {
        sub_account_id: formData.sub_account_id
    };
    resetCode(params).then((data: any) => {
        ElMessage({
            message: '短信已发送',
            type: 'success'
        });
    });
};
//确定重置
const initCodes = () => {
    const params = {
        sub_account_id: formData.sub_account_id,
        sms_code: qrcode.value
    };
    initPassword(params).then((data: any) => {
        passwordVisible.value = false;
        ElMessage({
            message: '密码重置成功',
            type: 'success'
        });
    });
};
//删除tag
const handleClose = (tag: any) => {
    selectDeparts.value.splice(selectDeparts.value.indexOf(tag as never), 1);
    formData.department_ids.splice(formData.department_ids.indexOf(tag.id as never), 1);
};
//打开选择部门
const Opendeparts = (val: number) => {
    dialogMember.value = JSON.parse(JSON.stringify(selectDeparts.value));
    departVisible.value = true;
    companyName.value = '';
};

//切换是否同步创建
const changeBox = (data: any) => {
    if (data && openType.value == 1 && Object.getOwnPropertyNames(work_user).length) {
        // 创建子账号点击同步创建才用同步数据
        isShow.value = true;
        work_user.gender ? (isSex.value = true) : (isSex.value = false);
        formData.sex = work_user.gender;
        work_user.position ? (isPosition.value = true) : (isPosition.value = false);
        formData.position = work_user.position;
        if (work_user.department.length == 0) {
            selectDeparts.value = [];
        } else {
            work_user.department ? (isUser.value = true) : (isUser.value = false);
            selectDeparts.value = work_user.department;
        }
    } else if (data) {
        isShow.value = true;
    } else {
        isShow.value = false;
        formData.enable_assistant = false;
    }
};
//获取手机号
const getPhoneNum = (data: any) => {
    if (data.length == 11) {
        getWorker(data);
    }
};
//通过手机号获取员工
const getWorker = (data: any) => {
    getWorkUser({
        mobile: data
    }).then((res: any) => {
        domember.value = res.work_user ? [res.work_user] : [];
        formData.execute_workuser_id = res.work_user ? getSetionId('id', domember.value) : [];
        if (res.account) {
            isRequired.value = false;
            formData.name = res.account!.name;
            res.account.sex ? (isSex.value = true) : (isSex.value = false);
            formData.sex = res.account.sex;

            res.account.position ? (isPosition.value = true) : (isPosition.value = false);
            formData.position = res.account.position;
            if (res.account.department.length == 0) {
                selectDeparts.value = [];
            } else {
                res.account.department ? (isUser.value = true) : (isUser.value = false);
                selectDeparts.value = res.account.department;
            }
            res.account.status ? (isStatus.value = true) : (isStatus.value = false);
            formData.status = res.account.status;
            res.account.role.length > 0 ? (isRole.value = true) : (isRole.value = false);
            formData.role_id = res.account.role[0].id;
            account = res.account;
        }
        if (res.work_user) {
            work_user = res.work_user;
        }
    });
};
// 打开员工组件
const opendept = (data: any) => {
    if (openType.value == 2 || isPosition) {
        DepartRef.value.departVisble = false;
    }
    if (openType.value !== 2 || !isPosition.value) {
        DepartRef.value.mobile = formData.phone;
        DepartRef.value.selectedMember = data;
        DepartRef.value.multiple = false;
        DepartRef.value.departVisble = true;
    }
};
// 保存员工
const getDepart = (res: any) => {
    domember.value = res;
    formData.execute_workuser_id = getSetionId('id', domember.value);
    DepartRef.value.departVisble = false;
    isShow.value = true;
};
//删除员工成员
const changedept = (res: any) => {
    domember.value = domember.value.filter((data: any) => res.includes(data.id));
    formData.execute_workuser_id = res;
    isShow.value = false;
};
// 表格的自适应高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
onMounted(() => {
    reSize(getTableH);
});
</script>

<style lang="scss" scoped>
.account-sub-main {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.btn-content {
    text-align: right;

    .add-btn {
        margin-bottom: 10px;
    }
}

.depart-content {
    display: flex;
    justify-content: space-between;

    .hover-detail {
        color: #535456;
        font-size: 14px;
    }

    .hover-detail-color {
        color: #ff6b00;
    }

    .hover-detail:hover {
        color: #ff6b00;
    }

    .select-detail {
        width: 40%;
        display: flex;
        justify-content: space-between;
        line-height: 30px;
    }

    .select-details {
        width: 150px;
    }

    .depart-detail {
        display: flex;
        flex-direction: column;

        .depart-btn {
            margin: 0;
        }
    }

    .no-data {
        display: flex;
        flex-direction: column;
        align-items: center;

        .no-img {
            margin: 30px 0 15px 15px;
            width: 150px;
            height: 120px;
        }

        .no-span {
            display: block;
            margin-right: 22px;
        }
    }
}

.form-tags {
    display: flex;
    width: 300px;
    flex-wrap: wrap;

    .tag-detail {
        margin-right: 10px;
    }
}

.detail-color {
    color: #ffc69e;
}

.local-color {
    color: #c3c3c3;
}

.tips-text {
    font-size: 14px;
    color: #969696;
    line-height: 50px;
}

.tips-detail {
    font-weight: 500;
    font-size: 16px;
    color: black;
}

:deep .el-table th.el-table__cell {
    background-color: #f9f9f9;
}

.content {
    position: relative;
    top: 20px;
    left: 0;
    right: 0;
    height: 100%;
    width: 100%;

    .main {
        position: absolute;
        height: calc(100% - 60px);
        width: 100%;
        top: 0;
        bottom: 60px;

        .el-scrollbar__view {
            height: 100%;
        }
    }
}
</style>
